package com.itheima.dao;

import com.itheima.domain.Role;
import com.itheima.domain.UserInfo;
import org.apache.ibatis.annotations.*;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface UserDao {

    @Select("select * from users where username=#{username}")
    @Results({
            @Result(id=true,column = "id",property = "id"),
            @Result(column = "username",property = "username"),
            @Result(column = "email",property = "email"),
            @Result(column = "password",property = "password"),
            @Result(column = "phoneNum",property = "phoneNum"),
            @Result(column = "status",property = "status"),
            @Result(column = "id",property = "roles",javaType = java.util.List.class,
                   many = @Many(select = "com.itheima.dao.RoleDao.findRoleByUserId"))
    })
    public UserInfo findByUsername(String username)throws Exception;

    @Select("select * from users")
    public List<UserInfo> findAll()throws Exception;

    @Insert("insert into users(email,username,password,phoneNum,status) value(#{email},#{username},#{password},#{phoneNum},#{status})")
    public void saveUser(UserInfo userInfo)throws Exception;

    @Select("select * from users where id = #{userid}")
    @Results({
            @Result(id=true,column = "id",property = "id"),
            @Result(column = "username",property = "username"),
            @Result(column = "email",property = "email"),
            @Result(column = "password",property = "password"),
            @Result(column = "phoneNum",property = "phoneNum"),
            @Result(column = "status",property = "status"),
            @Result(column = "id",property = "roles",javaType = java.util.List.class,
                    many = @Many(select = "com.itheima.dao.RoleDao.findRoleByUserId"))
    })
    UserInfo findById(int userid);

    @Select("select * from role where id not in (select roleId from users_role where userId=#{userid}) ")
    List<Role> findOtherRoles(int userid);

    @Insert("insert into users_role(userId,roleId) values(#{userId},#{roleId})")
    void addRoleToUser(@Param("userId") int userId,@Param("roleId") int roleId);
}
